﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Settings;
using System.Web;
using System.Net;

namespace SMSROUTER.Business
{
    public partial class SysChangeLog
    {
        public static void Insert(int UserID, string action, string machineName, string ipAddress)
        {
            using (SqlConnection conn = new SqlConnection(AppSetting.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"INSERT INTO SysChangeLog(UserID, Action, ActionDate, MachineName, IpAddress) 
                                        VALUES(@UserID, @Action, @ActionDate, @MachineName, @IpAddress)";
                    cmd.Parameters.AddWithValue("@UserID", UserID);
                    cmd.Parameters.AddWithValue("@Action", action);
                    cmd.Parameters.AddWithValue("@ActionDate", DateTime.Now);
                    cmd.Parameters.AddWithValue("@MachineName", machineName);
                    cmd.Parameters.AddWithValue("@IpAddress", ipAddress);
                    cmd.ExecuteNonQuery(); 
                }
            }
        }

        public static void Insert(int UserID, string action)
        {
            string ipAddress = "unknown";
            string hostName = "unknown";
            try
            {
                ipAddress = HttpContext.Current.Request.UserHostAddress;
            }
            catch { }
            Insert(UserID, action, hostName, ipAddress);
        }

        public static List<SysChangeLog> Paging(int currentPage, int pageSize, ref int totalRecord, int? userID)
        {
            using (var context = new DBDataContext(AppSetting.ConnectionString))
            {
                var resutl = context.SysChangeLogs.Where(p=>p.ActionDate >= DateTime.Now.Date.AddMonths(-3)).OrderByDescending(p => p.ChangeLogID).AsQueryable();
                if (userID != null)
                {
                    resutl = resutl.Where(p => p.UserID == userID);
                }
                totalRecord = resutl.Count();
                return resutl.Skip(((currentPage - 1) < 0 ? 0 : (currentPage - 1)) * pageSize).Take(pageSize).ToList();
            }
        }
    }
}
